var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session=require('express-session');
var timeout = require('connect-timeout');
var hbs=require("hbs");
var url = require('url');
var captchapng = require('captchapng');//验证码

var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');
var order = require('./routes/order');
var process = require('./routes/process');
var controller = require('./routes/controller');
var product = require('./routes/product');
var rework = require('./routes/rework');
var system = require('./routes/system');
var sign = require('./routes/sign');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));//所有模板注册
app.engine('html',hbs.__express);
app.set('view engine', 'html')
app.use(timeout('15s'));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  resave:true,//是否允许session重新设置，要保证session有操作的时候必须设置这个属性为true
  rolling:true,//是否按照原设定的maxAge值重设session同步到cookie中，要保证session有操作的时候必须设置这个属性为true
  saveUninitialized: false, //是否设置session在存储容器中可以给修改
  secret: 'productSourcetree',
  cookie: {maxAge: 1800* 1000}
}));

app.use(express.static(path.join(__dirname, 'public'))); //静态文件路径
app.use(function(req,res,next){
    var pathUrl = req.originalUrl;
    console.log('打印请求路径')
    console.log(req.originalUrl);
    if(!req.session.user){         
      if(pathUrl!='/login' && url.parse(pathUrl).pathname!='/account/getVerifyimg' && pathUrl!='/severError') { //通过判断控制用户登录后不能访问登录页面
         console.log("进来了？");
         console.log(pathUrl)
          return res.redirect('/login');//页面重定向；
      }else{
        console.log(2222);
        next();
      }
    }else if(req.session.user && pathUrl=='/account/loginOut'){
        delete req.session.user;
        return res.redirect('/login');//页面重定向； 
    }else{
        console.log(3333);
      next();
    }
})

app.get('/',indexRouter);
app.use('/login', loginRouter);
app.post('/logout',function(req,res){
    sign.nullDataReq(req,req.session.token,'/logout',"post",function(ResData){
        if(ResData!=""){
            if(JSON.parse(ResData).statusCode==200){
                delete req.session.user;
                delete req.session.token;
                delete req.session.role;
                res.send(ResData);
            }
        }else{
            res.send('暂时没有数据');
        }
    });
});
app.get('/account/getVerifyimg', function (req, res) {
    var code = '123456789';
    var length = 4;
    var randomcode = '';
    for (var i = 0; i < length; i++) {
        randomcode += code[parseInt(Math.random() * 1000) % code.length];
    }
    // 输出图
    req.session.code = randomcode;
    var p = new captchapng(100,36,parseInt(randomcode)); // width,height,numeric captcha
    p.color(255, 255, 255, 255);  // First color: background (red, green, blue, alpha)
    p.color(65, 65, 65, 255); // Second color: paint (red, green, blue, alpha)
    var img = p.getBase64();
    var imgbase64 = new Buffer(img,'base64');
    res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    res.end(imgbase64);
});
app.post('/changePassworPage',function(req,res){
  res.render('changePassword');
})
app.post('/changePassword',function(req,res){
  console.log(req.body);
  sign.dataReq(req,req.session.token,req.body,'changePassword',"post",function(ResData){
      if(ResData!=""){
          res.send(ResData);
      }
  });
})
app.post('/device/newPage',function(req,res){
  res.render('newpage',req.body);
})
app.post('/device/deviceDetail',function(req,res){
  res.render('deviceDetail',req.body);
})
app.post('/device/searchDevice',function(req,res){
  let data=req.body
  let searchdata={'type':parseInt(data.type),'searchString':data.searchString}
  sign.dataReq(req,req.session.token,searchdata,'device/searchDevice',"post",function(ResData){
      if(ResData!=""){
          res.send(ResData);
      }
  });
})

app.get('/main',function(req, res){
  res.render('main');
})
app.get('/severError',function(req, res){
  res.render('severError');
})
app.post('/upload/File',product.upload);

app.get('/order/list',function(req,res){   //这是生产详情和工序详情的回退，有三级，回第二级使用post,第一级使用get
    res.render('order/list');
})
app.post('/order/list',function(req,res){
  res.render('order/list',req.body);
})
app.get('/order/oldlist',function(req, res){
  res.render('order/oldlist');
})
app.get('/order/loadinglist',function(req, res){
  res.render('order/loadinglist');
})
app.get('/order/notBeginlist',function(req, res){
  res.render('order/notBeginlist');
})
app.post('/order/list/todayDevice',function(req, res){
  res.render('order/todayDevice');
})

app.get('/process/detailPage',function(req, res){
  res.render('order/detailPage',req.query);
})

app.post('/order/list/add',function(req, res){
  res.render('order/add');
})
app.post('/order/addOrder',order.addOrder);
app.post('/rework/reworkFile',rework.reworkFile);

app.post('/order/processStatistics',order.processStatistics);
app.post('/order/alldevice',order.alldevice);
app.post('/order/getOrderList',order.getOrderList);
app.post('/order/getChildOrderList',order.getChildOrderList); //获取子订单详情数据
app.post('/order/getOrderoldList',order.getOrderoldList)
app.post('/order/getloadinglist',order.getloadinglist)
app.post('/order/getNotBeginList',order.getNotBeginList)
app.post('/order/getMlti',order.getMlti)

app.post('/order/getTypeList',order.getTypeList)
app.post('/order/getConfigList',order.getConfigList)
app.post('/order/getControllerList',order.getControllerList)
app.post('/order/checkSN',order.checkSN)
app.post('/order/addProduct',order.addProduct)
app.post('/order/delChildOrder',order.delChildOrder)  //删除子订单
app.post('/order/updateinfoPage',function(req,res){
  res.render('order/editinfo',req.body);
})
app.post('/order/updateInfo',order.updateInfo)
app.post('/order/operateOrder',order.operateOrder)
app.post('/order/export',order.export) //导出
app.post('/order/list/detail',function(req,res){
  res.render('order/detail',req.body);
})
app.get('/order/childOrderDetails',function(req,res){ //这是订单详情新填加
  res.render('order/childOrderDetails',req.query);
})
app.post('/order/checkFile',function(req,res){ //这是订单详情新填加
  console.log(req.body);
  res.render('order/checkFile',req.body);
})

app.use('/order/orderDetails',function(req,res){   //这是生产详情和工序详情的回退，有三级，回第二级使用post,第一级使用get
  if(JSON.stringify(req.body) != "{}"){
    res.render('order/orderDetails',req.body);
  }else{
    res.render('order/orderDetails',req.query);
  }
})
// app.get('/order/processDetails',function(req,res){ //这是工序详情新填加  无意回退会退到一个post请求的
//   res.render('order/processDetails',req.query);
// })
app.use('/order/processDetails',function(req,res){  //回退执行的post
  if(JSON.stringify(req.body) != "{}"){
    res.render('order/processDetails',req.body);
  }else{
    res.render('order/processDetails',req.query);
  }
})
app.post('/order/addChildOrder',function(req,res){
  res.render('order/addChildOrder',req.body);
})  //提交子订单
app.post('/order/editChildOrder',function(req,res){ //这是子订单详情编辑
  res.render('order/editChildOrder',req.body);
})
app.get('/order/DeviceReportPage',function(req,res){ //这是订单详情新填加
  res.render('order/DeviceReportPage',req.query);
})
app.post('/order/updateChildOrderList',order.updateChildOrderList);
app.post('/order/addChildOrderList',order.addChildOrderList);

app.get('/order/processPage',function(req,res){
  res.render('order/processPage',req.query);
})
app.post('/order/getOrderController',order.getOrderController)
app.post('/index/todayFinishInfo',order.todayFinishInfo)
app.post('/index/todayFinishNum',order.todayFinishNum)
app.post('/index/orderSituation',order.orderSituation)
app.post('/index/getNewOrderInfo',order.getNewOrderInfo)
app.post('/index/statisticsOneMonth',order.statisticsOneMonth)
app.post('/order/processList',order.processList)
app.post('/order/productList',order.productList)
app.post('/order/orderProcessList',order.orderProcessList)
app.post("/order/saveProcessList",order.saveProcessList);
app.post("/order/getDeviceReportDate",order.getDeviceReportDate);

//控制器
app.get('/controller/list',function(req, res){
  res.render('controller/list');
})
app.post('/controller/controllerList',controller.controllerList)
app.post('/controller/addPage',function(req,res){
  res.render('controller/add');
})
app.post('/controller/editPage',function(req,res){
  res.render('controller/edit',req.body);
})
app.post('/controller/addController',controller.addController)
app.post('/controller/EditController',controller.EditController)
app.post('/controller/forbidden',controller.forbidden)

//产品
app.get('/product/list',function(req, res){
  res.render('product/list');
})
app.get('/product/productList',function(req, res){
  res.render('product/productList',req.query);
})
app.post('/product/getProductList',product.getProductList)
app.post("/product/getParameter",product.getParameter);
app.post('/product/list/add',function(req, res){
  res.render('product/productAdd',req.body);
})
app.post('/product/list/edit',function(req, res){
  res.render('product/productEdit',req.body);
})
app.post('/product/list/typeAdd',function(req, res){
  res.render('product/typeAdd',req.body);
})
app.post('/product/list/typeEdit',function(req, res){
  res.render('product/typeEdit',req.body);
})
app.post('/product/delProductConfig',product.delProductConfig) //删除订单配置
app.post('/product/delProductType',product.delProductType)     //删除订单类型
app.post('/product/list/parameterEdit',function(req, res){
  res.render('product/parameterEdit',req.body);
})
app.post('/product/list/parameterAdd',function(req, res){
  res.render('product/parameterAdd',req.body);
})
app.post('/product/addProductParameter',product.productParameter) 
app.post("/product/updateProductList",product.updateProductList);
app.post("/product/updateProductType",product.updateProductType);
app.post("/product/addProductList",product.addProductList);
app.post("/product/addProductType",product.addProductType);
app.post("/product/saveParameter",product.saveParameter);
app.post('/product/addparameter',function(req,res){   
    res.send({"list":[req.body],"message":"添加成功","statusCode":"200"});
})
var parameterData;
app.post('/product/saveParameterEdit',function(req,res){ 
 req.body.rows=JSON.parse(req.body.rows);
 parameterData = req.body;
  res.send({parameterData,"message":"添加成功","statusCode":"200"});
})
app.post('/product/getParameterEdit',function(req,res){  
  res.send({parameterData,"message":"添加成功","statusCode":"200"});
})

//产品类型
app.get('/product/typeList',function(req, res){
  res.render('product/typeList');
})
app.post('/product/getProductTypeList',product.getProductTypeList)

app.get('/menu',function(req,res){

  // 192.168.2.140:8080/getmodule
  sign.nullDataReq(req,req.session.token,'/getmodule',"post",function(ResData){
    if(ResData!=''){
			res.send(ResData);
		}else{
			res.send('暂时没有数据');
		}
});
  // res.send([
  //   {"name":"系统","icon":"fa-cog","children":[
  //     { "name":"用户", "url":"/user/list"},
  //     {"name":"角色", "url":"/role/list"},
  //   ]},
  //   {"name":"订单","icon":"fa-file-text", "children":[
  //       {"name":"所有订单", "url":"/order/list"},
  //       {"name":"未开始订单", "url":"/order/notBeginlist"},
  //       {"name":"已完成订单", "url":"/order/oldlist"},
  //       {"name":"进行中订单", "url":"/order/loadinglist"}
  //   ]},
  //   {"name":"工序","icon":"fa-list-alt", "children":[
  //       {"name":"工序方案", "url":"/processPlan"}
  //   ]},
  //   { "name":"控制器","icon":"fa-th","children":[
  //       {"name":"控制器", "url":"/controller/list"}
  //   ]},
  //   {"name":"产品","icon":"fa-suitcase", "children":[
  //       { "name":"产品类型", "url":"/product/typeList"},
  //       { "name":"产品配置", "url":"/product/list"}
  //   ]},
  //   {"name":"返工","icon":"fa-tasks","children":[
  //       {"name":"返工", "url":"/rework/list"}
  //   ]}

  // ])
})

//工序管理
app.get('/processPlan',function(req, res){
  res.render('process/list');
});
app.get('/process/list',function(req, res){
  res.render('process/processList',req.query);
})
app.post('/process/list/add',function(req, res){
  res.render('process/processSetAdd');
})
app.post('/process/list/edit',function(req, res){
  res.render('process/processSetEdit',req.body);
})                                              //工序集添加
app.post("/process/addProcessSchemeDemo",process.addProcessSchemeDemo);
                                                          //工序集编辑
app.post("/process/editProcessSchemeDemo",process.editProcessSchemeDemo);

app.post('/process/processListSn/edit',function(req, res){
     res.render('process/processListEditSn',req.body);
})
app.post('/process/processListSn/Add',function(req, res){
    res.render('process/processListAddSn',req.body);
})
app.post('/process/processList/add',function(req, res){
  res.render('process/processListAdd',req.body);
})
app.post('/process/processList/edit',function(req, res){
  res.render('process/processListEdit',req.body);
})
app.post('/process/addProcessParameter',process.processParameter) 
app.post("/process/schemeList",process.getSchemeList);
app.post("/process/processList",process.getProcessList);
app.post("/process/saveProcessList",process.saveProcessList);
app.post('/process/addProcess',function(req,res){
  res.send({"list":[req.body],"message":"添加成功","statusCode":"200"});
})
var processEdit;
app.post('/process/saveProcessListEdit',function(req,res){   //订单工序编辑后所有数据保存
  req.body.processList=JSON.parse(req.body.processList);
  processEdit = req.body;
  res.send({processEdit,"message":"修改成功","statusCode":"200"});
})
var rows; 
app.post('/process/getProcessListEdit',function(req,res){   //订单工序编辑后所有数据获取格式一致
  delete processEdit.orderId
  processEdit.rows=processEdit.processList
  delete processEdit.processList
  res.send(processEdit);
})
                         
var processTable;   //工序方案编辑后所有数据获取
app.post('/process/getProcessListEditTable1',function(req,res){   //订单工序编辑后所有数据获取一致
  delete processEdit.orderId
  processTable= processEdit.processList
  delete processEdit.processList
  res.send(processTable);
})
app.post('/process/delScheme',process.delScheme)     //删除订单类型

//返工
app.get('/rework/list',function(req, res){
  res.render('rework/list');
})
app.post('/rework/getList', rework.getList);
app.post('/rework/reworkReport',function(req, res){
  res.render('rework/reworkReport');
})
// app.post('/rework/reworkFile',rework.reworkFile);

//系统管理
app.get('/user/list',function(req,res){
  res.render('system/userList')
})
app.post('/user/getRoleList',system.userGetRoleList)
app.post('/user/getUserList',system.getUserList)
app.post('/user/list/add',function(req,res){
  var data;
  if(JSON.stringify(req.body) === '{}'){
    data = {'url': '/user/addUser','password':'DY123456'}
  }else{
    data = req.body
    data.roleId = req.body['role[id]']
    data.url ='/user/editUser'
    data.password =''
  }
  res.render('system/addUser',data)
})
app.post('/user/addUser',system.addUser)
app.post('/user/editUser',system.editUser)
app.post('/user/delUser',system.delUser)
app.get('/role/list',function(req,res){
  res.render('system/roleList')
})
app.post('/role/getRoleList',system.getRoleList)
app.post('/role/list/add',function(req,res){
  var data; 
  if(JSON.stringify(req.body) === '{}'){
    data = {'url': '/role/addRole'}
    
  }else{
    data = req.body
    data.url ='/role/editRole'
  }
  console.log(data);
  res.render('system/addRole',data)
})
app.post('/role/addRole',system.addRole)
app.post('/role/editRole',system.editRole)
app.post('/role/delRole',system.delRole)
app.post('/role/getRightInfoList',system.getRightInfoList)
app.post('/device/deivceInfo',rework.deviceInfo);
app.use(haltOnTimedout)       //登录超时
function haltOnTimedout (req, res, next) {
  if (!req.timedout) next()
}

app.use(function(req, res, next) {      // catch 404 and forward to error handler
  var err = new Error('Not Found'); 
  err.status = 404;
  next(err);
})

app.use(function(err, req, res, next) {  // error handler set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500 );
  if(err.status==503){
    console.log("进来吗？")
      res.render('severError'); 
  }else{
    console.log(err.status);
    console.log("500就是了")
      res.render('error');
  }
});

module.exports = app;
